package cn.dapeng.local;

import lombok.Data;

import java.util.Random;

public class ThreadLocalTest {

    static ThreadLocal<Integer> x = new ThreadLocal<>();

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                int data = new Random().nextInt();
                System.out.println(Thread.currentThread().getName() + " has put data: " + data);
                x.set(data);

                MyThreadScopeData.getThreadInstance().setName("name:" + data);
                MyThreadScopeData.getThreadInstance().setAge(data);


                new A().get();
                new B().get();
            }).start();
        }
    }


    static class A {
        public void get() {
            int data = x.get();
            System.out.println("A from " + Thread.currentThread().getName() + " get data: " + data
                    + " \n\t " + MyThreadScopeData.getThreadInstance().getName() + " \t" + MyThreadScopeData.getThreadInstance().getAge());
        }
    }

    static class B {
        public void get() {
            int data = x.get();
            System.out.println("B from " + Thread.currentThread().getName() + " get data: " + data
                    + " \n\t " + MyThreadScopeData.getThreadInstance().getName() + " \t" + MyThreadScopeData.getThreadInstance().getAge());
        }
    }

}

@Data
class MyThreadScopeData {
    private String name;
    private int age;

    private MyThreadScopeData() {
    }

    private static ThreadLocal<MyThreadScopeData> threadLocal = new ThreadLocal<>();

    public static MyThreadScopeData getThreadInstance() {
        MyThreadScopeData instance = threadLocal.get();
        if (instance == null) {
            instance = new MyThreadScopeData();
            threadLocal.set(instance);
        }
        return instance;
    }
}
